package com.zzyl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.exceptions.ExceptionUtil;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zzyl.base.BaseDto;
import com.zzyl.base.BaseEntity;
import com.zzyl.base.PageResponse;
import com.zzyl.base.ResponseResult;
import com.zzyl.dto.ReservationDto;
import com.zzyl.entity.NursingProject;
import com.zzyl.entity.Reservation;
import com.zzyl.enums.BasicEnum;
import com.zzyl.enums.ReservationStatus;
import com.zzyl.exception.BaseException;
import com.zzyl.mapper.ReservationMapper;
import com.zzyl.service.ReservationService;
import com.zzyl.utils.UserThreadLocal;
import com.zzyl.vo.TimeCountVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
@Transactional
public class ReservationServiceImpl implements ReservationService {

    @Resource
    private ReservationMapper reservationMapper;

    /**
     * 添加预约
     */
    @Override
    public ResponseResult add(ReservationDto dto) {
        // TODO 如果取消预约次数超过3次，则不需要再进行预约
        Reservation reservation = BeanUtil.toBean(dto, Reservation.class);
        //设置初始状态为：待报到
        reservation.setStatus(ReservationStatus.PENDING.getOrdinal());
        try {
            return ResponseResult.success(reservationMapper.insert(reservation));
        } catch (Exception e) {
            log.info(ExceptionUtil.getMessage(e));
            throw new BaseException(BasicEnum.TIME_ALREADY_RESERVATED_BY_PHONE);
        }
    }

    @Override
    public PageResponse<Reservation> queryByPage(Integer pageNum, Integer pageSize, Integer status, Long userId) {
        PageHelper.startPage(pageNum, pageSize);
        Page<Reservation> list = reservationMapper.queryByPage(pageNum, pageSize, status, userId);
        return PageResponse.of(list, Reservation.class);
    }


    @Override
    public int deleteReservation(Long id) {
        return reservationMapper.deleteReservation(id);
    }

    @Override
    public ResponseResult updateStatus(Reservation reservation) {
        int i = reservationMapper.updateStatus(reservation);
        return ResponseResult.success(i);
    }

    /**
     * 查询每个时间段剩余预约次数
     * @param time 时间 日
     * @return 每个时间段剩余预约次数
     */
    @Override
    public List<TimeCountVo> countByTime(LocalDateTime time) {
        LocalDateTime endTime = time.plusHours(24);
        return reservationMapper.countByTime(time, endTime);
    }

}